package itsur.arquitecturas.pipeandfilter;

/**************************************************************************************
 ** Class name: MergeRejectFilter
 ** Author: A.J. Lattanze
 ** 
 *
 ** Date: 12/3/99
 ** Version 1.0
 ***************************************************************************************
 ** Purpose: Assignment 1 for SE 17-655, Architectures for Software Systems.  This
 ** assignment is designed to illustrate a pipe and filter architecture.  For the 
 ** instructions, refer to the assignment write-up.
 **
 ** Abstract: This class is intended to be a filter that will collect the input from the
 **		 course filters and merge them into a single output file.
 ** 
 ** Pseudo Code:
 **
 ** 	connect to CourseFilter1 for input
 ** 	connect to CourseFilter2 for input
 ** 	Open output file
 **	while not done
 **		read char1 from input pipe1
 **		read char2 from input pipe2
 **		string1 = string1 + char1
 **		string2 = string2 + char2
 **		write string1 to output file
 **		write string2 to output file
 **	end while
 **	close pipes
 **	close file
 **
 ** Running the program
 **
 ** 	See MainFilter.java
 **
 ** Modification Log
 **************************************************************************************
 ** David Morales Orozco
 ** Modificaciones: 
 **************************************************************************************/
import java.io.*;

public class MergeRejectFilter extends Thread {
	// Declarations

	String OutputFileName;

	// Create local pipes to that will connect to CourseFilter filters

	PipedReader InputPipe1 = new PipedReader();
	PipedReader InputPipe2 = new PipedReader();

	public MergeRejectFilter(String OutputFileName, PipedReader InputPipe1,
			PipedReader InputPipe2) {
		this.OutputFileName = OutputFileName;

		try {
			// Connect InputPipe1 to CourseFilter1

			this.InputPipe1 = InputPipe1;
			System.out.println("MergeRejectFilter:: Connecting InputPipe #1. ");

			// Connect InputPipe2 to CourseFilter2

			this.InputPipe2 = InputPipe2;
			System.out.println("MergeRejectFilter:: Connecting InputPipe #2. ");

		} // try

		catch (Exception Error) {
			System.out.println("MergeRejectFilter::Error connecting CourseFilter. ");
		} // catch

	} // Constructor

	// This is the method that is called when the thread is started in
	// MainFilter

	public void run() {
		// Declarations

		boolean Done1, Done2; // Flags for reading from each pipe
//		String userPathName; // Part of output file name
		String directory; // Part of output file name
		File fileObject; // Output file object
		BufferedWriter bout = null; // Output file buffer writer object

		// Open and/or create the output file
		// Check for file existence

		fileObject = new File(OutputFileName);

		if (!fileObject.exists()) {
			// File doesn't exist. Separate filename from the
			// directory path for creation.

			OutputFileName = fileObject.getName();
			directory = fileObject.getAbsolutePath();
			directory = directory.substring(0,
					(directory.length() - OutputFileName.length()));

			if (!fileObject.exists()) {
				// Create directory

				fileObject = new File(directory);
				fileObject.mkdirs();
				System.out.println("MergeFilter::Created directory: "
						+ directory);
				fileObject = new File(directory, OutputFileName);

			} // if
		} // if

		// Create a buffered writer

		try {
			// Create a buffered writer

			bout = new BufferedWriter(new FileWriter(fileObject));

		} // try

		catch (IOException IOError) {
			System.out.println("MergeFilter::Buffered Writer Creation Error ");

		} // catch

		// Begin process data from the input pipes

		try {
			// Declarations

			Done1 = false; // Indicates when you are done reading
			// on pipe #1
			Done2 = false; // Indicates when you are done reading
			// on pipe #2
			char[] CharacterValue1 = new char[1]; // Needs to be an array for
													// easy
			// conversion to string
			int IntegerCharacter1; // the integer value read from the pipe
			char[] CharacterValue2 = new char[1]; // Needs to be an array for
													// easy
			// conversion to string
			int IntegerCharacter2; // the integer value read from the pipe
			String LineOfText1 = ""; // line of text from inputpipe #1
			String LineOfText2 = ""; // line of text from inputpipe #2
			boolean Write1 = false; // line of text to write to the output
			// file inputpipe #1
			boolean Write2 = false; // line of text to write to the output
			// file inputpipe #2
			// Main loop for reading data

			while (!Done1 || !Done2) {
				// Read pipe #1
				if (!Done1) {
					IntegerCharacter1 = InputPipe1.read();
					CharacterValue1[0] = (char) IntegerCharacter1;

					if (IntegerCharacter1 == -1) // pipe #1 is closed
					{
						Done1 = true;
						System.out.println("MergeRejectFilter::Pipe #1 Closed ");
						try {
							InputPipe1.close();
						} catch (Exception Error) {
							System.out
									.println("MergeRejectFilter::Error closing pipes ");
						} // catch
					} else {
						if (IntegerCharacter1 == '\n') // end of text string
						{
							System.out.print("MergeRejectFilter::Received: "
									+ LineOfText1);
							System.out.println(" on pipe #1 ");
							Write1 = true;
						} else {
							LineOfText1 += new String(CharacterValue1);
						} // if
					} // if
				} // if

				// Read pipe #2
				if (!Done2) {
					IntegerCharacter2 = InputPipe2.read();
					CharacterValue2[0] = (char) IntegerCharacter2;

					if (IntegerCharacter2 == -1) // pipe #2 is closed
					{
						Done2 = true;
						System.out.println("MergeFilter::Pipe #2 Closed ");
						try {
							InputPipe2.close();
						} catch (Exception Error) {
							System.out
									.println("MergeRejectFilter::Error closing pipes ");
						} // catch
					} else {
						if (IntegerCharacter2 == '\n') // end of text string
						{
							System.out.print("MergeRejectFilter::Received: "
									+ LineOfText2);
							System.out.println(" on pipe #2 ");
							Write2 = true;
						} else {
							LineOfText2 += new String(CharacterValue2);
						} // if
					} // if
				} // if

				// Write text line from pipe #2

				if (Write1) {
					Write1 = false;

					try {
						System.out.println("MergeRejectFilter::Writing: "
								+ LineOfText1);
						//modificaciones por itsur.java
						//se hace un split para poder obtener el last name y el curso los cuales corresponden
						//a los indices 1 y 2
						//324123123 Franklin GSIA 12323 21323 12123
						String dividir[] = LineOfText1.split(" ");
						
						//bout.write(LineOfText1 + "\n\r");
						bout.write(dividir[1] + " " +dividir[2] + "\n\r");
					} // try
					catch (Exception IOError) {
						System.out.println("MergeRejectFilter::Write Error ");
					} // catch

					LineOfText1 = "";

				} // if

				// Write text line from pipe #2

				if (Write2) {
					Write2 = false;

					try {
						System.out.println("MergeRejectFilter::Writing: "
								+ LineOfText2);
						//modificaciones por itsur.java
						//se hace un split para poder obtener el last name y el curso los cuales corresponden
						//a los indices 1 y 2
						//324123123 Franklin GSIA 12323 21323 12123
						String dividir[] = LineOfText2.split(" ");
						
						//bout.write(LineOfText1 + "\n\r");
						bout.write(dividir[1] + " " +dividir[2] + "\n\r");
						

					} // try
					catch (Exception IOError) {
						System.out.println("MergeRejectFilter::Write Error ");
						
					} // catch

					LineOfText2 = "";

				} // if
			} // while
		} // try

		catch (Exception Error) {
			System.out.println("MergeRejectFilter::Interrupted. " + Error.getMessage());
			Error.printStackTrace(); 

		} // catch

		// Close the output file

		try {
			System.out.println("MergeRejectFilter::Closing output file ");
			bout.close();
		} catch (Exception Error) {
			System.out.println("MergeRejectFilter::Error closing output file ");
		} // catch
	} // run
} // class